package com.situ.mall.controller;

import com.situ.mall.constant.RedisConstant;
import com.situ.mall.util.QiniuUtils;
import com.situ.mall.util.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/uploadImage")
    @ResponseBody
    public Result uploadImage(MultipartFile file) {
        System.out.println("UploadController.uploadImage");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = file.getOriginalFilename();// a.png
        String extension = FilenameUtils.getExtension(filename);
        //35f5ee8be8f548159ed6b1e8c1e63fc7.png
        String newFilename = uuid + "." + extension;

        /*String filePath = "D:\\mypic\\" + newFilename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        try {
            QiniuUtils.upload2Qiniu(file.getBytes(), newFilename);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //将上传的图片保存到redis中
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE, newFilename);

        return Result.ok("上传成功", QiniuUtils.URL+ newFilename);
    }
}
